/*
 * Created by JFormDesigner on Mon Jun 05 19:29:34 CST 2023
 */

package gui.admin;

import dao.ProductCategoryDao;
import dao.ProductDao;
import entity.Product;
import entity.ProductCategory;
import gui.admin.tablemodel.ProductTableModel;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import javax.swing.*;

/**
 * @author Liubuzhu
 */
public class ManageProductFrame extends JFrame {
    ProductCategoryDao productCategoryDao = new ProductCategoryDao();
    public ManageProductFrame() throws Exception {
        initComponents();
    }

    private void initComponents() throws Exception {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents  @formatter:off
        label1 = new JLabel();
        label2 = new JLabel();
        label3 = new JLabel();
        label4 = new JLabel();
        label5 = new JLabel();
        label6 = new JLabel();
        label7 = new JLabel();
        label8 = new JLabel();
        productId = new JTextField();
        productId.setEditable(false);
        productName = new JTextField();
        productName.setEditable(false);
        expiryDate = new JTextField();
        storageLocation = new JTextField();
        purchasePrice = new JTextField();
        salePrice = new JTextField();
        stockQuantity = new JTextField();
        stockQuantity.setEditable(false);
        productCategoryCbox = new JComboBox();
        productPicture = new JLabel();
        scrollPane1 = new JScrollPane();
        table1 = new JTable();
        updateBtn = new JButton();
        deleteBtn = new JButton();
        cancelBtn = new JButton();

        List productCategoryList = productCategoryDao.getAllProductCategory();
        for (int i = 0; i < productCategoryList.size(); i++) {
            ProductCategory productCategory = (ProductCategory) productCategoryList.get(i);
            productCategoryCbox.addItem(new ProductCategory(productCategory.getCategoryId(),productCategory.getCategoryName()){
                public String toString(){
                    String productCategoryName = productCategory.getCategoryName();
                    return productCategoryName;
                }
            });
        }

        //======== this ========
        setTitle("\u5546\u54c1\u7ba1\u7406\u9875\u9762");
        setPreferredSize(new Dimension(1200, 800));
        setVisible(true);
        var contentPane = getContentPane();
        contentPane.setLayout(null);

        //---- label1 ----
        label1.setText("\u5546\u54c1\u7f16\u53f7");
        label1.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        contentPane.add(label1);
        label1.setBounds(40, 40, 75, 30);

        //---- label2 ----
        label2.setText("\u5546\u54c1\u7c7b\u522b");
        label2.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        contentPane.add(label2);
        label2.setBounds(40, 85, 100, 30);

        //---- label3 ----
        label3.setText("\u5546\u54c1\u540d\u79f0");
        label3.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        contentPane.add(label3);
        label3.setBounds(40, 130, 75, 30);

        //---- label4 ----
        label4.setText("\u4fdd\u8d28\u671f");
        label4.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        contentPane.add(label4);
        label4.setBounds(40, 175, 75, 30);

        //---- label5 ----
        label5.setText("\u5b58\u653e\u4f4d\u7f6e");
        label5.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        contentPane.add(label5);
        label5.setBounds(40, 220, 75, 30);

        //---- label6 ----
        label6.setText("\u8fdb\u4ef7");
        label6.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        contentPane.add(label6);
        label6.setBounds(40, 265, 75, 30);

        //---- label7 ----
        label7.setText("\u552e\u4ef7");
        label7.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        contentPane.add(label7);
        label7.setBounds(40, 310, 75, 30);

        //---- label8 ----
        label8.setText("\u5e93\u5b58\u6570\u91cf");
        label8.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        contentPane.add(label8);
        label8.setBounds(40, 355, 75, 30);
        contentPane.add(productId);
        productId.setBounds(165, 40, 185, 35);
        contentPane.add(productName);
        productName.setBounds(165, 125, 185, 35);
        contentPane.add(expiryDate);
        expiryDate.setBounds(165, 175, 185, 35);
        contentPane.add(storageLocation);
        storageLocation.setBounds(165, 220, 185, 35);
        contentPane.add(purchasePrice);
        purchasePrice.setBounds(165, 265, 185, 35);
        contentPane.add(salePrice);
        salePrice.setBounds(165, 310, 185, 35);
        contentPane.add(stockQuantity);
        stockQuantity.setBounds(165, 355, 185, 35);
        contentPane.add(productCategoryCbox);
        productCategoryCbox.setBounds(165, 80, 185, 35);

        //---- productPictuer ----
        productPicture.setText("该商品暂未设置图片");
        contentPane.add(productPicture);
        productPicture.setBounds(25, 405, 340, 340);

        //======== scrollPane1 ========
        {
            table1.setModel(new ProductTableModel());//设置表格的数据模型
            scrollPane1.setViewportView(table1);
        }
        contentPane.add(scrollPane1);
        scrollPane1.setBounds(390, 40, 733, 350);

        //---- updateBtn ----
        updateBtn.setText("\u4fee\u6539");
        updateBtn.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        contentPane.add(updateBtn);
        updateBtn.setBounds(520, 485, 95, 50);

        //给修改按钮添加点击事件
        updateBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                String productIdTemp = productId.getText();//获取文本输入框的内容
                String productNameTemp = productName.getText();
                int index = productCategoryCbox.getSelectedIndex();
                ProductCategory productCategory = (ProductCategory) productCategoryList.get(index);
                String categoryIdTemp = productCategory.getCategoryId();
                String categoryNameTemp = productCategory.getCategoryName();
                String expiryDateTemp = expiryDate.getText();
                String storageLocationTemp = storageLocation.getText();
                float purchasePriceTemp = Float.parseFloat(purchasePrice.getText());
                float salePriceTemp = Float.parseFloat(salePrice.getText());
                int stockQuantityTemp = Integer.parseInt(stockQuantity.getText());
                String productPictureTemp = productName.getText() + ".jpg";


                Product product = new Product(productIdTemp,categoryIdTemp,categoryNameTemp,productNameTemp,expiryDateTemp,storageLocationTemp,purchasePriceTemp,salePriceTemp,stockQuantityTemp,productPictureTemp);
                ProductDao productDao = new ProductDao();
                boolean result = productDao.updateProduct(product);//调用修改方法
                if(productId.getText().equals("")){
                    JOptionPane.showMessageDialog(null,"请先选择要修改的商品");
                }else{
                    if(result){
                        JOptionPane.showMessageDialog(null,"修改商品信息成功");
                        ProductTableModel productTableModel = null;
                        try {
                            productTableModel = new ProductTableModel();
                        } catch (Exception ex) {
                            throw new RuntimeException(ex);
                        }
                        table1.setModel(productTableModel);//刷新表格
                    }else{
                        JOptionPane.showMessageDialog(null,"修改商品信息失败");
                    }
                }
            }
        });


        //---- deleteBtn ----
        deleteBtn.setText("\u5220\u9664");
        deleteBtn.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        contentPane.add(deleteBtn);
        deleteBtn.setBounds(695, 485, 95, 50);

        //给删除按钮添加点击事件
        deleteBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int res = JOptionPane.showConfirmDialog(null,"你确定要删除该商品吗？","删除确认",JOptionPane.YES_NO_OPTION);
                if(res == 0){
                    if (productId.getText().equals("")){
                        JOptionPane.showMessageDialog(null,"请先选择要删除的商品！");
                    }else {
                        Product product = new Product();
                        product.setProductId(productId.getText());
                        ProductDao productDao = new ProductDao();
                        try {
                            String msgSting = productDao.deleteProduct(product);
                            JOptionPane.showMessageDialog(null,msgSting);
                            ProductTableModel productTableModel = new ProductTableModel();
                            table1.setModel(productTableModel);//刷新表格
                        } catch (Exception ex) {
                            throw new RuntimeException(ex);
                        }
                    }
                }
            }
        });

        //---- cancelBtn ----
        cancelBtn.setText("返回");
        cancelBtn.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 16));
        contentPane.add(cancelBtn);
        cancelBtn.setBounds(865, 485, 95, 50);

        cancelBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                dispose();//关闭当前窗口
                try {
                    AdminMainFrame adminMainFrame = new AdminMainFrame();//回到管理员主界面
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });

        //给表格添加鼠标点击事件
        table1.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                //super.mouseClicked(e);
                int row = table1.getSelectedRow();//获取鼠标当前点击的行下标
                //获取点击行商品编号
                String productIdTemp = (String) table1.getValueAt(row,0);
                String productNameTemp = (String) table1.getValueAt(row,1);
                String categoryIdTemp = (String) table1.getValueAt(row,2);
                String categoryNameTemp = (String) table1.getValueAt(row,3);
                String expiryDateTemp = (String) table1.getValueAt(row,4);
                String storageLocationTemp = (String) table1.getValueAt(row,5);
                float purchasePriceTemp = Float.parseFloat((String) table1.getValueAt(row,6));
                float salePriceTemp = Float.parseFloat((String) table1.getValueAt(row,7));
                String stockQuantityTemp = (String) table1.getValueAt(row,8);
                //设置商品图片
                ImageIcon imageIcon = new ImageIcon("./image/product/" + productNameTemp + ".jpg");
                productPicture.setIcon(imageIcon);
                //设置文本输入框内容
                productId.setText(productIdTemp);
                productName.setText(productNameTemp);
                expiryDate.setText(expiryDateTemp);
                storageLocation.setText(storageLocationTemp);
                purchasePrice.setText(String.valueOf(purchasePriceTemp));
                salePrice.setText(String.valueOf(salePriceTemp));
                stockQuantity.setText(stockQuantityTemp);
                //设置下拉选项框
                for (int i = 0; i < productCategoryList.size(); i++) {
                    ProductCategory productCategory = (ProductCategory) productCategoryList.get(i);
                    if (productCategory.getCategoryId().equals(categoryIdTemp)){
                        productCategoryCbox.setSelectedIndex(i);
                    }
                }
            }
        });

        {
            // compute preferred size
            Dimension preferredSize = new Dimension();
            for(int i = 0; i < contentPane.getComponentCount(); i++) {
                Rectangle bounds = contentPane.getComponent(i).getBounds();
                preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
                preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
            }
            Insets insets = contentPane.getInsets();
            preferredSize.width += insets.right;
            preferredSize.height += insets.bottom;
            contentPane.setMinimumSize(preferredSize);
            contentPane.setPreferredSize(preferredSize);
        }
        pack();
        setLocationRelativeTo(getOwner());
        // JFormDesigner - End of component initialization  //GEN-END:initComponents  @formatter:on
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables  @formatter:off
    private JLabel label1;
    private JLabel label2;
    private JLabel label3;
    private JLabel label4;
    private JLabel label5;
    private JLabel label6;
    private JLabel label7;
    private JLabel label8;
    private JTextField productId;
    private JTextField productName;
    private JTextField expiryDate;
    private JTextField storageLocation;
    private JTextField purchasePrice;
    private JTextField salePrice;
    private JTextField stockQuantity;
    private JComboBox productCategoryCbox;
    private JLabel productPicture;
    private JScrollPane scrollPane1;
    private JTable table1;
    private JButton updateBtn;
    private JButton deleteBtn;
    private JButton cancelBtn;
    // JFormDesigner - End of variables declaration  //GEN-END:variables  @formatter:on
    public static void main(String[] args) throws Exception {
        ManageProductFrame manageProductFrame = new ManageProductFrame();
    }
}
